import os
import shutil
from datetime import datetime


def backup_file(src_path):
    """备份文本文件 (保留原始格式) """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    base_name = os.path.basename(src_path)
    backup_name =f"{os.path.splitext(base_name)[0]}_backup_{timestamp}"
    backup_path = os.path.join("backups", backup_name)

    os.makedirs("backups", exist_ok=True)


    try:
        shutil.copy2(src_path, backup_path)
        print(f"成功备份到: {backup_path}")
        return True
    except Exception as e:
        print(f"备份失败: {e}")
        return False

backup_file("data,txt")


def incremental_backup(src_path):
    """增量备份 (比较修改时间) """
    if not os.path.exists(src_path):
        print("源文件不存在")
        return
    backup_dir = "backups"
    os.makedirs(backup_dir, exist_ok=True)
    src_mtime = os.path.getmtime(src_path)
    latest_backuP = None

    for fname in os.listdir(backup_dir):
        if fname.startswith(os.path.basename(src_path)):
            backup_mtime = os.path.getmtime(os.path.join(backup_dir, fname))
            if not latest_backup or backup_mtime > latest_backup[1]:
                latest_backup = (fname, backup_mtime)


    if not latest_backup or src_mtime > latest_backup[1]:
        return backup_file(src_path)
    else:
        print("文件未修改, 跳过备份")
        return False

def register_user(username, password, email):
    """注册用户 (存储到文本文件)"""
    user_data = f"{username},{password},{email}\n"

    try:
        with open("users.txt", "a", encoding="utf-8") as f:
            f.write(user_data)
        print("注册成功! ")
        return True
    except IOError as e:
        print(f"注册失败: {e}")
        return True
    except IOError as e:
        print(f"注册失败: {e}")
        return False


register_user("alice","p@ssw0rd","alice@ecxample.com")

import json

def json_register(username, password, email):
    """注册新用户 (JSON格式存储)"""
    new_user = {
    "username": username,
    "password": password,
    "email" :email,
    "register_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}

    user = []

    try:
        with open("users.json", "r", encoding="utf-8") as  f:
            users= json.load(f)
    except (FileNotFoundError, json.JSONDecodeError):
        pass
    if any(u["username"] == username for u in users):
        print("用户名已存在")
        return False
    users.append(new_user)
    try:
        with open("users.json", "w", encoding="utf-8") as f:
            json.dump(users, f, indent=2, ensure_ascii=False)
        print("注册成功！")
        return True
    except IOError as e:
        print(f"注册失败: {e}")
        return False


json_register("bob","bob123","bob@example.com")
import hashlib
import getpass
def hash_password(password):
    """使用SHA-256哈希密码"""
    return hashlib.sha256(password.encode()).hexdigest()
def secure_register():
    """安全注册流程"""
    username = input("请输入用户名： ").strip()
    password = getpass.getpass("请输入密码： ")
    email = input("请输入邮箱： ").strip()

    user_data = {
        "username": username,
        "password_hash": hash_password(password),
        "email": email,
        "register_time": datetime.now().isoformat
    }

import json
import hashlib
from pathlib import Path


class UserSystem:
    def __init__(self, db_file="user_json"):
        self.db_file = Path(db_file)
        self.backup_dir = Path("backups")
        self.users =self._load_users()
    def _load_users(self):
        """加载用户数据"""
        if not self.db_file.existsz():
            return []

        try:
            with open(self.db_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError) as e:
            print(f"加载用户数据失败： [e]")
            return []
    def _backup_db(self):
        """备份用户数据库"""
        self.backup_dir.mkdir(exist_ok=True)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = self.backup_dir / f"users_backup_{timestamp}.json"

        try:
            shutil.copy2(self.db_file, backup_file)
            print(f"数据已备份到： {backup_file}")
        except Exception as e:
            print(f"备份失败： {e}")
    def register(self, username, password, email):
        """注册新用户"""
        if any(u["username"] == username for u in self.users):
            print("用户名已存在")
            return False
        self.users.append({
            "username": username,
            "password_hash": hashlib.sha256(password.encode()).hexdigest(),
            "email":email,
            "register_time": datetime.now().isoformate()
        })
        try:
            with open(self.db_self, "w",encoding="utf-8") as f:
                json.dump(self.users, f, indent=2)
                self._backup_db()
                print("注册成功！")
                return True
        except IOError as e:
            print(f"保存失败： {e}")
            return False




system = UserSystem()
system.register("charlie","secure123","charlie@example.com")


